<template>
  <div class="publish-notice">
    <p>发布公关的区域与物业电话</p>
    <el-table
      :data="tableData"
      :row-style="{ height: '30px' }"
      style="width: 100%"
      max-height="150"
    >
      <el-table-column prop="name" label="区域名称"></el-table-column>
      <el-table-column prop="tel" label="物业电话"></el-table-column>
    </el-table>
    <h3>公告信息：</h3>
    <el-form ref="formNotice" :model="form" :rules="rules">
      <el-form-item prop="notice">
        <el-input
          type="textarea"
          v-model="form.notice"
          :autosize="{ minRows: 2 }"
          placeholder="请输入公告内容"
        ></el-input>
      </el-form-item>
    </el-form>
    <div class="btn-group">
      <el-button type="primary" @click="publish">确定</el-button>
      <el-button type="danger" @click="cancel">取消</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, reactive } from 'vue';
import { addNotice } from '../apis/index';
import { ElMessage } from 'element-plus';

const props = defineProps({
  selectInfo: {
    type: Array,
    default: () => [],
  },
});
//取消事件时向回上一级传递数据
const emit = defineEmits(['cancel']);

const tableData = ref([]);
const formNotice = ref(null);
const form = reactive({
  notice: '',
});

const rules = reactive({
  notice: [{ required: true, message: '公告内容不能为空', trigger: 'blur' }],
});

//确定按钮点击事件
const publish = () => {
  //验证表单
  formNotice.value.validate((valid) => {
    if (valid) {
      //获取当前时间，格式2025年4月26日13:25:32
      const now = new Date();
      const year = now.getFullYear();
      const month = now.getMonth() + 1;
      const date = now.getDate();
      const hour = now.getHours();
      const minute = now.getMinutes();
      const second = now.getSeconds();
      const time = `${year}年${month}月${date}日${hour}:${minute}:${second}`;
      //组装公告数据
      const data = {
        time: time,
        content: form.notice,
      };
      //发送请求
      addNotice(data)
        .then((res) => {
          //发布成功
          if (res.data.status == 1) {
            ElMessage.success('公告发布成功');
            emit('cancel');
          } else {
            ElMessage.error('发布失败，请稍后再试');
          }
        })
        .catch((err) => {
          //发布失败
          ElMessage.error('发布失败，请稍后再试');
        });
    }
  });
};

//取消按钮点击事件
const cancel = () => {
  emit('cancel');
};

watch(
  () => props.selectInfo,
  (newVal) => {
    tableData.value = newVal;
  },
  { immediate: true, deep: true }
);
</script>

<style lang="scss" scoped>
.publish-notice {
  p {
    margin-bottom: 10px;
  }
  .el-table {
    :deep(.el-table__header) {
      font-size: 14px;
      tr,
      th,
      td {
        text-align: center;
        line-height: 24px;
      }
    }
  }
  h3 {
    margin-top: 20px;
    font-size: 16px;
  }
  .btn-group {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
    .el-button {
      font-size: 14px;
    }
  }
}
</style>
